package edu.cibertec.sicsolutions.util;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

public class JsonMVCUtil {
      
	public static void jsonResponse(JSONObject jsonData,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception
	{
		// check whether it is script Tag...
		// which is called by JSON
		boolean scriptTag = false;
		String cb = request.getParameter("callback");
		if (cb != null) {
			scriptTag = true;
			response.setContentType("text/javascript");
		} else {
			response.setContentType("application/x-json");
		}
 
		PrintWriter out = response.getWriter();
		if (scriptTag) {
			out.write(cb + "(");
		}			
		response.getWriter().print(jsonData);
		if (scriptTag) {
			out.write(");");
		}
	}
	
	public static void jsonResponse(String jsonData,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception
	{
		// check whether it is script Tag...
		// which is called by JSON
		boolean scriptTag = false;
		String cb = request.getParameter("callback");
		if (cb != null) {
			scriptTag = true;
			response.setContentType("text/javascript");
		} else {
			response.setContentType("application/x-json");
		}
 
		PrintWriter out = response.getWriter();
		if (scriptTag) {
			out.write(cb + "(");
		}			
		response.getWriter().print(jsonData);
		if (scriptTag) {
			out.write(");");
		}
	}
}
